package com.baizhi.aspect;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.LogDAO;
import com.baizhi.entity.Admin;
import com.baizhi.entity.Log;
import com.baizhi.utils.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Configuration
public class LogAspect {
    @Autowired
    private LogDAO logDAO;

    @After("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void logAspect(JoinPoint joinPoint){
//        创建Log对象
        Log l = new Log();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        Admin amdin = (Admin) session.getAttribute("login");
        l.setAdminId(amdin.getId());
        l.setLogDate(new Date());
//        获取用户的ip
//        String ip = request.getRemoteAddr();
        String ip = IPKit.getIpAddrByRequest(request);
        l.setLogIp(ip);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String content = annotation.content();
        String type = annotation.type();
        l.setLogContent(content);
        l.setLogType(type);
        logDAO.insert(l);
    }
}
